package com.yogurt.gulimall.product.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yogurt.gulimall.product.service.CategoryBrandRelationService;
import com.yogurt.gulimall.product.vo.Catalog2Vo;
import com.yogurt.gulimall.product.vo.Catalog3Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yogurt.common.utils.PageUtils;
import com.yogurt.common.utils.Query;

import com.yogurt.gulimall.product.dao.CategoryDao;
import com.yogurt.gulimall.product.entity.CategoryEntity;
import com.yogurt.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类信息
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = baseMapper.selectList(null);
        // 得到所有的一级分类
        List<CategoryEntity> level1 = list.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .map((menu) ->{
                    menu.setChildren(getChildren(menu,list));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return level1;
    }

    // 删除菜单数据
    @Override
    public void removeMenus(List<Long> asList) {
        // TODO 删除前判断是否菜单有引用，有，，否则则不能删除，能删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath;
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 获取二级三类商品分类（页面渲染）
     * @return Map<String, List<Catalog2Vo>>
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalog() {
        /**
         * 加入缓存逻辑，redis
         */
        // 判断缓存中是否有数据
        String catalog = redisTemplate.opsForValue().get("catalog");
        if (StrUtil.isBlank(catalog)) {
            System.out.println("缓存不命中...从数据库获取...");
            // 如果缓存中没有，则查询数据库，并存入缓存中
            Map<String, List<Catalog2Vo>> catalogFromDb = getCatalogFromDbWithRedisLock();
//            String str = JSONUtil.toJsonStr(catalogFromDb);
//            redisTemplate.opsForValue().set("catalog", str);
            return catalogFromDb;
        }
        // 如果缓存中有数据，则直接返回
        Map<String, List<Catalog2Vo>> result = JSONUtil.toBean(catalog, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        }, false);
        System.out.println("缓存命中...从缓存中获取...");
        return result;
    }

    /**
     * 从数据库中查询商品分类数据(本地锁方式)
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogFromDbWithLocalLock() {

        // 只要是同一把锁，就能锁住这个需要这个锁的所有线程
        // 本地锁：synchronized (this),Spring Boot的所有组件在容器中默认都是单例的
        // synchronized , JUC(lock) 都是本地锁，分布式情况下，要想锁住所有，必须使用分布式锁
        synchronized (this) {
            return getDataFromDb();
        }
    }

    /**
     * 分布式锁方式
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogFromDbWithRedisLock() {
        // 生成随机字符串
        String uuid = UUID.randomUUID().toString();
        // 占用redis分布式锁，设置过期时间，原子性设置
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(lock)) {
            // 占锁成功
            Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            }finally {
                // 删除锁,使用Lua脚本(防止删除其他线程的锁)
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList("lock"), uuid);
            }
            return dataFromDb;
        }else {
            // 加锁失败，等待重试
            // 休眠1000毫秒，重试
            // 自旋的方式
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogFromDbWithRedisLock();
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        String catalog = redisTemplate.opsForValue().get("catalog");
        if (StrUtil.isNotEmpty(catalog)) {
            Map<String, List<Catalog2Vo>> result = JSONUtil.toBean(catalog, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            }, false);
            return result;
        }

        /**
         * 优化：
         * 将查询数据库，只查询一次
         */
        // 获取所有的数据
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);


        // 获取所有一级分类
        List<CategoryEntity> level1List = getChildrenByCatId(categoryEntityList, 0L);
        Map<String, List<Catalog2Vo>> result = level1List.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), value -> {
            // 根据一级分类id查询二级分类
//            List<CategoryEntity> level2List = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", value.getCatId()));

            // 优化
            List<CategoryEntity> level2List = getChildrenByCatId(categoryEntityList, value.getCatId());

            List<Catalog2Vo> catalog2Vos = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(level2List)) {
                catalog2Vos = level2List.stream().map(level2 -> {
                    // 封装数据
                    Catalog2Vo catalog2Vo = new Catalog2Vo();
                    // 一级父分类id
                    catalog2Vo.setCatalog1Id(value.getCatId().toString());
                    // 二级分类id
                    catalog2Vo.setId(level2.getCatId().toString());
                    // 二级分类名称
                    catalog2Vo.setName(level2.getName());
                    // 根据二级分类id查询三级分类集合
//                    List<CategoryEntity> level3List = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", level2.getCatId()));

                    // 优化
                    List<CategoryEntity> level3List = getChildrenByCatId(categoryEntityList, level2.getCatId());

                    // 封装三级分类数据
                    if (ObjectUtil.isNotEmpty(level3List)) {
                        List<Catalog3Vo> catalog3List = level3List.stream().map(level3 -> {
                            Catalog3Vo catalog3Vo = new Catalog3Vo();
                            // 二级分类id
                            catalog3Vo.setCatalog2Id(level2.getCatId().toString());
                            // 三级分类id
                            catalog3Vo.setId(level3.getCatId().toString());
                            // 三级分类名称
                            catalog3Vo.setName(level3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3List);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        // 查询出结果，放入缓存
        String str = JSONUtil.toJsonStr(result);
        redisTemplate.opsForValue().set("catalog", str);
        return result;
    }

    /**
     * 查询当前分类下所有子分类
     * @param categoryEntityList 所有商品分类数据
     * @param catId 商品分类id
     * @return List<CategoryEntity>
     */
    private List<CategoryEntity> getChildrenByCatId(List<CategoryEntity> categoryEntityList, Long catId) {
        return categoryEntityList.stream().filter(item -> item.getParentCid().equals(catId)).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }

    // 递归遍历菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(root.getCatId()))
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, all));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
        return children;
    }
}
